package com.wsc.wsckeeper.activities;

import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.wsc.wsckeeper.R;
import com.wsc.wsckeeper.activities.base.BaseActivity;
import com.wsc.wsckeeper.listeners.TextWatcherImpl;
import com.wsc.wsckeeper.managers.PreferenceManager;
import com.wsc.wsckeeper.managers.ResourceManager;
import com.wsc.wsckeeper.managers.ScreenManager;

public class LoginActivity extends BaseActivity {

	private LinearLayout dialog;
	private View hide;
	private Button login;
	private EditText password;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_login);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		password.setText("");
		password.setError(null);
	}

	@Override
	public void initComponents() {
		dialog = (LinearLayout) findViewById(R.id.dialog);
		hide = (View) findViewById(R.id.hide);
		login = (Button) findViewById(R.id.login);
		password = (EditText) findViewById(R.id.password);
	}

	@Override
	public void initValues() {
		getActionBar().hide();

		dialog.setVisibility(View.INVISIBLE);

		getHander().postDelayed(new Runnable() {

			public void run() {
				if (PreferenceManager.getInstance().getNeedLogin()) {
					dialog.setVisibility(View.VISIBLE);
				} else {
					ScreenManager.getInstance().forward(LoginActivity.this, BaseTabActivity.class);
				}
			}
		}, 500);
	}

	@Override
	public void initListeners() {
		hide.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				ScreenManager.getInstance().forward(LoginActivity.this, BaseTabActivity.class);
				return false;
			}
		});

		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (PreferenceManager.getInstance().getPassword().equalsIgnoreCase(password.getText().toString())) {
					ScreenManager.getInstance().forward(LoginActivity.this, BaseTabActivity.class);
				} else {
					password.setError(ResourceManager.getStringValue(R.string.alert_password_wrong));
				}
			}
		});

		password.addTextChangedListener(new TextWatcherImpl() {
			@Override
			public void afterTextChanged(Editable s) {
				password.setError(null);
			}
		});
	}

	@Override
	public void onBackPressed() {
		// KApplication.getInstance().closeApplication();
		moveTaskToBack(true);
		finish();
	}
}